<?php

class Mailing_list extends MY_Controller {
    
    function __construct() {
        parent::__construct();
    }
 
    public function subscribe() {
        $this->form_validation->set_rules('email', 'Email', 'required|valid_email');
        if ($this->form_validation->run() == FALSE) {
            $this->session->set_flashdata('flashMessage', 'Please enter a valid email address');
            $this->session->set_flashdata('flashMessageType', 'danger');
            redirect('');
        }
        
        $mailingList = new Mailinglist();
        $email = $this->input->post('email');
        $mailingList->where('email', $email)->get();
        if (!$mailingList->exists()) {
            $mailingList = new Mailinglist();
            $mailingList->email = $email;
            $mailingList->ip_address = $this->input->ip_address();
            $mailingList->save();
            $this->session->set_flashdata('flashMessage', 'You have successfully subscribed to our Mailing List!');
            $this->session->set_flashdata('flashMessageType', 'success');
        } else {
            $this->session->set_flashdata('flashMessage', 'You are already subscribed to our Mailing List!');
            $this->session->set_flashdata('flashMessageType', 'danger');
        }
        redirect('');
    }
    
    public function unsubscribe() {
        $this->form_validation->set_rules('email', 'Email', 'required|valid_email');
        if ($this->form_validation->run() == FALSE) {
            $this->session->set_flashdata('flashMessage', 'Please enter a valid email address');
            $this->session->set_flashdata('flashMessageType', 'danger');
            redirect('');
        }
        $mailingList = new Mailinglist();
        $email = $this->input->post('email');
        $mailingList->where('email', $email)->get();
        if ($mailingList->exists()) {
            $mailingList->delete();
            $this->session->set_flashdata('flashMessage', 'You have successfully unsubscribed from our Mailing List.');
            $this->session->set_flashdata('flashMessageType', 'success');
        } else {
            $this->session->set_flashdata('flashMessage', 'Email does not exist to our mailing list.');
            $this->session->set_flashdata('flashMessageType', 'danger');
        }
    }

}

/* End of file mailinglist.php */
/* Location: ./application/controllers/mailinglist.php */